import datetime

from django.http import HttpResponse
from django.shortcuts import get_object_or_404

from htmock.models import *
import htmock.util.http


def meta_to_headers(meta):
    """Convert a Django environment object `meta` to a dict of headers."""
    nice = lambda s: '-'.join(w.capitalize() for w in s.split('_'))
    result = {}
    for key in meta:
        if key.startswith('HTTP_'):
            new_key = nice(key[5:])
            result[new_key] = meta[key]
        elif key in ('CONTENT_LENGTH', 'CONTENT_TYPE'):
            new_key = nice(key)
            result[new_key] = meta[key]
    return result


def mock(request, label):
    """Handle `request` for the actual mock resource with the given `label`."""
    resource = get_object_or_404(MockResource, label=label)
    
    TracedRequest(
        resource=resource,
        received_on=datetime.datetime.now(),
        remote_addr=request.META.get('REMOTE_ADDR', ''),
        method=request.method,
        headers=meta_to_headers(request.META),
        get_params=request.GET,
        post_params=request.POST,
        query_string=request.META.get('QUERY_STRING', ''),
        data=request.raw_post_data
    ).save()
    
    response = HttpResponse(resource.entity_body)
    response.status_code = resource.status_code
    for header in resource.headers.all():
        response[header.field_name] = header.field_value
    return response
